<?php
namespace backend\controllers;

use Yii;
use yii\filters\AccessControl;
use yii\web\Controller;
use yii\filters\VerbFilter;
use yii\web\HttpException;
use yii\web\NotFoundHttpException;
use yii\web\ForbiddenHttpException;
use yii\web\Session;

/**
 * Sms controller
 */
class SmsController extends Controller
{
    /**
     * @inheritdoc
     */
    public function behaviors()
    {
        return [
            'access' => [
                'class' => AccessControl::className(),
                'rules' => [
                    [
                        'actions' => [ 'error','send','send-login-code'],
                        'allow' => true,
                    ],
                    [
                        'actions' => [ 'index'],
                        'allow' => true,
                        'roles' => ['@'],
                    ],
                ],
            ],

        ];
    }

    /**
     * @inheritdoc
     */
    public function actions()
    {
        return [
            'error' => [
                'class' => 'yii\web\ErrorAction',
            ],
        ];
    }

    public function actionSendLoginCode(){
        $mobile = Yii::$app->request->post('mobile');
        $code = $this->createCode();
        $content = "本次验证码为".$code."，您正在登录纽仁云客管理系统，打死也不告诉别人哦";
        if($this->send($mobile,$content)===true){
            //检查session是否打开
            if(!Yii::$app->session->isActive){
                Yii::$app->session->open();
            }
            //验证码和短信发送时间存储session
            Yii::$app->session->set('login_sms_code',$code);
            Yii::$app->session->set('login_sms_time',time());
            echo 'Success';
        }
        else{
            echo  'Failed';
        }
    }

    public function createCode(){
        $code = '';
        for($i=1;$i<=6;$i++){
            $str = mt_rand(0,9);
            $code = $str.$code;
        }
        return $code;
    }

    public function send($mobile,$content){
        $this->layout = null;
        return Yii::$app->smser->send($mobile,$content);
    }

}
